package com.mynews.activities.detail;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.mynews.R;
import com.mynews.activities.App;
import com.mynews.adapter.MutiCommentAdp;
import com.mynews.bean.CommentBean;
import com.mynews.databinding.ActivityDetailBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
@SuppressLint("StaticFieldLeak")
public class DetailVM extends AndroidViewModel {
    public static MutableLiveData<String> title=new MutableLiveData<>(),likeCount=new MutableLiveData<>(),collectionCount=new MutableLiveData<>(),commentCount=new MutableLiveData<>(),content=new MutableLiveData<>(),classification=new MutableLiveData<>(),time=new MutableLiveData<>(),source=new MutableLiveData<>();
    public static MutableLiveData<Boolean> isLike=new MutableLiveData<>(),isCollect=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    public static DetailActivity detailActivity;
    private ActivityDetailBinding binding;
    private final List<CommentBean> data=new ArrayList<>();
    public DetailVM(@NonNull Application application) {super(application);}
    public void setBinding(ActivityDetailBinding binding, DetailActivity detailActivity,CollapsingToolbarLayout toolBarLayout) {
        DetailVM.detailActivity =detailActivity;
        this.binding=binding;
        //初始化或者观察界面数据
        title.observe(detailActivity, toolBarLayout::setTitle);
        title.setValue(App.newsBean.title);
        content.setValue(App.newsBean.content);
        classification.setValue("所属分类:"+App.newsBean.type);
        source.setValue("来源:"+App.newsBean.user.nickname);
        time.setValue(App.newsBean.time);
        commentCount.setValue("评论(0)");
        isLike.setValue(false);
        isCollect.setValue(false);
        likeCount.setValue("点赞(0)");
        collectionCount.setValue("收藏(0)");
        //设置适配器,以及列表点击长按方法
        binding.setAdp(new MutiCommentAdp(detailActivity, data));
        binding.detailCommentList.setOnItemClickListener((parent, view, position, id) -> {
            CommentBean bean = data.get(position);
            if (bean.isComment){
                EditText reply=new EditText(detailActivity);
                AlertDialog.Builder dialog=new AlertDialog.Builder(detailActivity);
                dialog.setTitle("回复").setView(reply).setPositiveButton("确定", (dialog1, which) -> {
                    if (reply.getText().toString().equals("")){
                        Toast.makeText(detailActivity, "请输入内容", Toast.LENGTH_SHORT).show();
                    }else {
                        JSONObject jo=new JSONObject();
                        try {
                            jo.put("commentId",bean.id);
                            jo.put("newsId",App.newsBean.id);
                            jo.put("replyOwnerId",App.user.objectId);
                            jo.put("content",reply.getText().toString());
                            BmobApi.post(jo, "https://api2.bmob.cn/1/classes/reply", new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                    detailActivity.runOnUiThread(() -> Toast.makeText(detailActivity, "回复失败:"+e.getMessage(), Toast.LENGTH_SHORT).show());
                                }
                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) {
                                    //吧回复的内容添加到Comment当作relation
                                    BmobApi.get("https://api2.bmob.cn/1/classes/reply?where={\"commentId\":\""+bean.id+"\"}", new Callback() {
                                        @Override
                                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                        }
                                        @Override
                                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                            try {
                                                assert response.body() != null;
                                                JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                                                JSONArray relationArr=new JSONArray();
                                                for (int i = 0; i < ja.length(); i++) {
                                                    relationArr.put(new JSONObject().put("__type","Pointer").put("className","reply").put("objectId",ja.getJSONObject(i).getString("objectId")));
                                                }
                                                JSONObject jo=new JSONObject();
                                                jo.put("__op","AddRelation");
                                                jo.put("objects",relationArr);
                                                BmobApi.put(new JSONObject().put("reply",jo), "https://api2.bmob.cn/1/classes/comment/"+bean.id, false, new Callback() {
                                                    @Override
                                                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                                        detailActivity.runOnUiThread(DetailVM.this::refreshComment);
                                                    }
                                                    @Override
                                                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                                                        detailActivity.runOnUiThread(DetailVM.this::refreshComment);
                                                    }
                                                });
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).setNeutralButton("取消",null).show();
            }else{
                Toast.makeText(detailActivity, "暂不支持回复他人的回复", Toast.LENGTH_SHORT).show();
            }
        });
        binding.detailCommentList.setOnItemLongClickListener((parent, view, position, id) -> {
            CommentBean bean = data.get(position);
            AlertDialog.Builder dialog=new AlertDialog.Builder(detailActivity);
            if (bean.isComment){
                    //用户是发布者或者评论者都可删
                    if (App.newsBean.user.objectId.equals(App.user.objectId)||App.user.objectId.equals(bean.ownerId)){
                        dialog.setTitle("提示").setMessage("是否删除?").setNeutralButton("取消",null).setPositiveButton("删除", (dialog12, which) -> {
                            BmobApi.delete("https://api2.bmob.cn/1/classes/comment/" + bean.id, new Callback() {
                                @Override public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                    detailActivity.runOnUiThread(DetailVM.this::refreshComment);
                                }@Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                                    detailActivity.runOnUiThread(DetailVM.this::refreshComment);
                                }
                            });
                            //查询本评论的所有回复,然后删了
                            BmobApi.get("https://api2.bmob.cn/1/classes/reply?where="+URLEncoder.encode("{\"$relatedTo\":{\"object\":{\"__type\":\"Pointer\",\"className\":\"comment\",\"objectId\":\""+bean.id+"\"},\"key\":\"reply\"}}"), new Callback() {
                                @Override public void onFailure(@NotNull Call call,@NotNull IOException e) { }
                                @Override public void onResponse(@NotNull Call call,@NotNull Response response) {
                                    try {
                                        assert response.body()!=null;
                                        JSONArray ja=new JSONObject(response.body().string()).getJSONArray("results");
                                        for(int i = 0; i < ja.length();i++) {
                                            BmobApi.delete("https://api2.bmob.cn/1/classes/reply/"+ja.getJSONObject(i).getString("objectId"), new Callback() {
                                                @Override public void onFailure(@NotNull Call call,@NotNull IOException e){
                                                    detailActivity.runOnUiThread(DetailVM.this::refreshComment);
                                                }
                                                @Override public void onResponse(@NotNull Call call,@NotNull Response response){
                                                    detailActivity.runOnUiThread(DetailVM.this::refreshComment);
                                                }
                                            });
                                        }
                                    }catch(Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }).show();
                    }
                }else{
                    String ownerId="";
                    for (CommentBean b:data) {
                        if (bean.ifReplyCommentId.equals(b.id)){
                             ownerId = b.ownerId;
                            break;
                        }
                    }
                    boolean is;//用以判断是否为评论者
                    if (ownerId.equals("")){
                        is=false;
                    }else {
                        is=App.user.objectId.equals(ownerId);
                    }
                    //用户是发布者或者评论者或者回复者都可删，此处的ownerId是回复者
                    if (App.newsBean.user.objectId.equals(App.user.objectId)||App.user.objectId.equals(bean.ownerId)||is){//任一成立则删，其他用户无权限
                        dialog.setTitle("提示").setMessage("是否删除?").setNeutralButton("取消",null).setPositiveButton("删除", (dialog12, which) -> BmobApi.delete("https://api2.bmob.cn/1/classes/reply/"+bean.id, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e){
                                detailActivity.runOnUiThread(() -> refreshComment());
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response){
                                detailActivity.runOnUiThread(() -> refreshComment());
                            }
                        })).show();
                    }
                }
            return true;
        });
        //获取评论及回复
        refreshComment();
        refreshLikeAndCollection();//刷新点赞，收藏
        addFactor();//增加影响因子用来推荐算法
    }
    private static void refreshLikeAndCollection() {
        BmobApi.get("https://api2.bmob.cn/1/classes/like?where="+ URLEncoder.encode("{\"newsId\":\""+App.newsBean.id+"\"}"), new Callback() {
            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    likeCount.postValue("点赞("+ja.length()+")");
                    boolean have=false;
                    for (int i = 0; i < ja.length(); i++) {
                        if (ja.getJSONObject(i).getString("userId").equals(App.user.objectId)){
                             have = true;
                            break;
                        }
                    }
                    isLike.postValue(have);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        BmobApi.get("https://api2.bmob.cn/1/classes/collection?where="+ URLEncoder.encode("{\"newsId\":\""+App.newsBean.id+"\"}"), new Callback() {
            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    collectionCount.postValue("收藏("+ja.length()+")");
                    boolean have=false;
                    for (int i = 0; i < ja.length(); i++) {
                        if (ja.getJSONObject(i).getString("userId").equals(App.user.objectId)){
                            have = true;
                            break;
                        }
                    }
                    isCollect.postValue(have);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //每次访问，都要增加影响因子，用以判断权重，实现推荐算法
    private void addFactor() {
        BmobApi.get("https://api2.bmob.cn/1/classes/factor?include=user&order=-createdAt&where="+ URLEncoder.encode("{\"userId\":\""+ App.user.objectId+"\"}"), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    if (ja.length()==0){
                        JSONObject jo=new JSONObject();
                        jo.put("userId",App.user.objectId);
                        jo.put("user",new JSONObject().put("__type","Pointer").put("className","_User").put("objectId",App.user.objectId));
                        jo.put("type1",0);
                        jo.put("type2",0);
                        jo.put("type3",0);
                        jo.put("type4",0);
                        jo.put("type5",0);
                        jo.put("type6",0);
                        jo.put("type7",0);
                        jo.put("type"+App.getTypeByName(App.newsBean.type),1);
                        BmobApi.post(jo, "https://api2.bmob.cn/1/classes/factor", new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e){}
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response){ }
                        });
                    }else{
                        JSONObject jo=new JSONObject().put("type"+App.getTypeByName(App.newsBean.type),new JSONObject().put("__op","Increment").put("amount",1));
                        BmobApi.put(jo, "https://api2.bmob.cn/1/classes/factor/"+ja.getJSONObject(0).getString("objectId"), false, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {}
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {}
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void onFabClick(View view){
        EditText comment=new EditText(detailActivity);
        comment.setHint("请输入评论内容");
        AlertDialog.Builder dialog=new AlertDialog.Builder(detailActivity);
        dialog.setTitle("评论").setView(comment).setPositiveButton("确定", (dialog1, which) -> {
            if (!comment.getText().toString().equals("")){
                JSONObject jo=new JSONObject();
                try {
                    jo.put("commentOwnerId",App.user.objectId);
                    jo.put("newsId",App.newsBean.id);
                    jo.put("content",comment.getText().toString());
                    BmobApi.post(jo, "https://api2.bmob.cn/1/classes/comment", new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            detailActivity.runOnUiThread(() -> Toast.makeText(detailActivity, "评论失败:"+e.getMessage(), Toast.LENGTH_SHORT).show());
                        }
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                            refreshComment();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else{
                Toast.makeText(detailActivity, "请输入评论内容", Toast.LENGTH_SHORT).show();
            }
        }).setNeutralButton("取消",null).show();
    }
    /**
     * 回复和评论俩表且又要组合加载显示的方式:二级加载完后先显示一级再显示二级
     */
    private void refreshComment() {
        data.clear();
        BmobApi.get("https://api2.bmob.cn/1/classes/comment?include=reply&order=-createdAt&where="+ URLEncoder.encode("{\"newsId\":\""+App.newsBean.id+"\"}"), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    commentCount.postValue("评论("+ja.length()+")");
                    //获取到所有评论id，ja，再通过评论id获取reply有该评论的回复
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        int finalI = i;
                        BmobApi.get("https://api2.bmob.cn/1/classes/reply?where="+URLEncoder.encode("{\"$relatedTo\":{\"object\":{\"__type\":\"Pointer\",\"className\":\"comment\",\"objectId\":\""+jo.getString("objectId")+"\"},\"key\":\"reply\"}}"), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                detailActivity.runOnUiThread(() ->{
                                    try {
                                        JSONObject jo = ja.getJSONObject(finalI);
                                        data.add(new CommentBean(true,jo.getString("objectId"),jo.getString("commentOwnerId"),jo.getString("content"),""));
                                        assert response.body() != null;
                                        JSONArray replys = new JSONObject(response.body().string()).getJSONArray("results");
                                        for (int i = 0; i < replys.length(); i++) {
                                            JSONObject reply = replys.getJSONObject(i);
                                            data.add(new CommentBean(false,reply.getString("objectId"),reply.getString("replyOwnerId"),reply.getString("content"),reply.getString("commentId")));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    binding.getAdp().notifyDataSetChanged();
                                });
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //根据数据监听的绑定事件~
    @BindingAdapter("bindCollect")
    public static void bindCollect(ImageView imageView,MutableLiveData<Boolean> is){
        if (is.getValue()){
            imageView.setImageResource(R.drawable.collected);
        }else{
            imageView.setImageResource(R.drawable.collect);
        }
    }
    @BindingAdapter("bindLike")
    public static void bindLike(ImageView imageView,MutableLiveData<Boolean> is){
        if (is.getValue()){
            imageView.setImageResource(R.drawable.liked);
        }else{
            imageView.setImageResource(R.drawable.like);
        }
    }
    public static void like(View view){
        BmobApi.get("https://api2.bmob.cn/1/classes/like?where="+ URLEncoder.encode("{\"userId\":\""+App.user.objectId+"\",\"newsId\":\""+App.newsBean.id+"\"}"), new Callback() {
            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    if (ja.length()>0){
                        BmobApi.delete("https://api2.bmob.cn/1/classes/like/"+ja.getJSONObject(0).getString("objectId"), new Callback() {
                            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refreshLikeAndCollection();
                            }
                        });
                        isLike.postValue(false);
                    }else{
                        JSONObject jo=new JSONObject();
                        jo.put("userId",App.user.objectId);
                        jo.put("newsId",App.newsBean.id);
                        BmobApi.post(jo, "https://api2.bmob.cn/1/classes/like", new Callback() {
                            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refreshLikeAndCollection();
                            }
                        });
                        isLike.postValue(true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public static void collect(View view){
        BmobApi.get("https://api2.bmob.cn/1/classes/collection?where="+ URLEncoder.encode("{\"userId\":\""+App.user.objectId+"\",\"newsId\":\""+App.newsBean.id+"\"}"), new Callback() {
            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    if (ja.length()>0){
                        //删了
                        BmobApi.delete("https://api2.bmob.cn/1/classes/collection/"+ja.getJSONObject(0).getString("objectId"), new Callback() {
                            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refreshLikeAndCollection();
                            }
                        });
                        isCollect.postValue(false);
                    }else{
                        JSONObject jo=new JSONObject();
                        jo.put("userId",App.user.objectId);
                        jo.put("newsId",App.newsBean.id);
                        BmobApi.post(jo, "https://api2.bmob.cn/1/classes/collection", new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e){}
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refreshLikeAndCollection();
                            }
                        });
                        isCollect.postValue(true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public static void tipOff(View view){
        EditText et=new EditText(detailActivity);
        et.setHint("请输入举报内容");
        AlertDialog.Builder dialog=new AlertDialog.Builder(detailActivity);
        dialog.setTitle("提示").setView(et).setPositiveButton("提交", (dialog1, which) -> {
            if (et.getText().toString().equals("")){
                Toast.makeText(detailActivity, "请输入举报内容", Toast.LENGTH_SHORT).show();
            }else{
                try {
                    JSONObject jo=new JSONObject();
                    jo.put("userId",App.user.objectId);
                    jo.put("user",new JSONObject().put("objectId",App.user.objectId).put("__type","Pointer").put("className","_User"));
                    jo.put("news",new JSONObject().put("objectId",App.newsBean.id).put("__type","Pointer").put("className","news"));

                    jo.put("newsOwner",new JSONObject().put("objectId",App.newsBean.user.objectId).put("__type","Pointer").put("className","_User"));


                    jo.put("content",et.getText().toString());
                    jo.put("process","待受理");
                    BmobApi.post(jo, "https://api2.bmob.cn/1/classes/tipoff", new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            detailActivity.runOnUiThread(() -> Toast.makeText(detailActivity, "提交失败"+e.getMessage(), Toast.LENGTH_SHORT).show());
                        }
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                            detailActivity.runOnUiThread(() -> Toast.makeText(detailActivity, "感谢您的反馈", Toast.LENGTH_SHORT).show());
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).setNeutralButton("取消",null).show();
    }
}